package org.itzheng

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.lang.Exception
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * Title:全局扩展函数<br>
 * Description: <br>
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-7-14.
 */
///**
// *在子线程加载
// */
//@Throws(Exception::class)
//public suspend fun <T> Call<T>.exec(): T {
//    return suspendCoroutine { continuation ->
//        enqueue(object : Callback<T> {
//            override fun onResponse(call: Call<T>, response: Response<T>) {
//                val body = response.body()
//                if (body != null) continuation.resume(body)
//                else continuation.resumeWithException(RuntimeException("response body is null"))
//            }
//
//            override fun onFailure(call: Call<T>, t: Throwable) {
//                t.printStackTrace()
////                continuation.resumeWithException(t)
//                continuation.resumeWithException(Exception("网络连接失败"))
//            }
//        })
//    }
//}

/**
 * int转dp
 */
fun Int.dp(context: Context): Int {
    val scale: Float = context.resources.displayMetrics.density
    return (this * scale + 0.5f).toInt()
}

/**
 * float转dp
 */
fun Float.dp(context: Context): Int {
    val scale: Float = context.resources.displayMetrics.density
    return (this * scale + 0.5f).toInt()
}

/**
 * 直接设置 LinearLayoutManager
 */
fun RecyclerView.setLinearAdapter(adapter: RecyclerView.Adapter<*>) {
    this.layoutManager = LinearLayoutManager(context)
    this.adapter = adapter
}

/**
 * 直接设置 GridLayoutManager
 */
fun RecyclerView.setGridAdapter(adapter: RecyclerView.Adapter<*>, spanCount: Int) {
    this.layoutManager = GridLayoutManager(context, spanCount)
    this.adapter = adapter
}

/**
 * int 转布尔类型
 */
fun Int.toBoolean(): Boolean {
    if (this <= 0) {
        return false
    }
    return true
}

/**
 * 布尔类型转int
 */
fun Boolean.toInt(): Int {
    if (this) {
        return 1;
    }
    return 0;
}

/**
 * 可以指定到位置，如果默认的，就无法指定到打印位置
 */
fun Exception.print() {
    java.lang.Exception(this.message).printStackTrace()
}
